package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeExceptionEnum;
import com.atguigu.common.exception.GulimallRunTimeException;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GuliMallProductException {
   //专门捕获参数校验失败错误异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        ///  log.info("数据校验出现的问题：{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> dataMap = new HashMap<>(16);
            bindingResult.getFieldErrors().forEach(s -> {
                String field = s.getField();
                String message = s.getDefaultMessage();
                dataMap.put(field, message);
            });
    return R.error(BizCodeExceptionEnum.VAILD_EXCEPTION.getCode(), BizCodeExceptionEnum.VAILD_EXCEPTION.getMessage()).put("data", dataMap);

    }

    @ExceptionHandler(value = GulimallRunTimeException.class)
    public R GuliMallAllException(GulimallRunTimeException e){
        return R.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = Throwable.class)
    public R GuliMallAllException(Throwable e){
        log.error("错误原因：{}",e.getMessage());
        return R.error(500, e.getMessage());
    }
}
